<template>
  <div class="bg-white">
    <div class="container-title">基础信息</div>
    <Form :label-width="120" :rules="rule" ref="form" :model="form">
      <Row class="pr">
        <Col span="12">
          <FormItem label="合同名称: " prop="name">
            <Input placeholder="合同名称" :readonly='readOnly' v-model="form.name" :maxlength="60"/>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="合同编号: " prop="sn">
            <Input placeholder="合同编号" :readonly='readOnly' v-model="form.sn" :maxlength="60"/>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="预签时间: " prop="preStartDate">
            <DatePicker :readonly="readOnly" v-model="preTimeRange" type="daterange" show-week-numbers placement="right" placeholder="选择预签时间" style="width: 200px"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="合同时间: " prop="startDate">
            <DatePicker :readonly="readOnly" v-model="changeContTime" type="daterange" show-week-numbers placement="right" placeholder="选择合同时间" style="width: 200px"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="适用门店: " prop="storeTypeId">
            <SelectList :disabled="readOnly" v-model="form.storeTypeId" listType="storeTypeList" />
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="合同内容: " prop="content">
            <div class='contract-content-editer' style="position:relative">
              <div class="tinymce-head-shade" v-if="isLook"></div>
              <div class="tinymce-box-shade" ref="conBox"  v-if="isLook"></div>
              <div class="pl pr">
                <Editor id='tinymce' v-model='form.content' :init='init'></Editor>
              </div>
            </div>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="备注: " prop="remark">
            <Input :readonly='readOnly' placeholder="备注" v-model="form.remark" />
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="12">
          <FormItem label="状态: " prop="status">
            <Select v-model="form.status" filterable clearable :placeholder="placeholder" :disabled='readOnly'>
              <Option
                v-for="item in contractTypeList"
                :disabled="item.disabled"
                :key="item.value"
                :label="item.text"
                :value="item.value">
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { getOriginData, uploadImageUrl, uploadFlashUrl, uploadMediaUrl, uploadFileUrl, preFixPath, formatDate } from '@/util'
  import SelectList from "~/SelectList";
  import tinymce from 'tinymce/tinymce'
  import 'tinymce/themes/modern/theme'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  export default {
    components: {
      SelectList,
      Editor
    },
    computed: {
      ...mapGetters(['user']),
      preTimeRange: {
        get() {
          return [this.form.preStartDate, this.form.preEndDate]
        },
        set(val) {
          this.form.preStartDate = formatDate(val[0], true)
          this.form.preEndDate = formatDate(val[1], true)
        }
      },
      changeContTime: {
        get() {
          return [this.form.startDate, this.form.endDate]
        },
        set(val) {
          if (val[0].valueOf() < new Date(this.form.preEndDate).valueOf()) {
            this.$Message.info('合同时间只能选择大于预签结束时间的时间段')
          }
          this.form.startDate = formatDate(val[0], true)
          this.form.endDate = formatDate(val[1], true)
        }
      },
    },
    props: {
      form: {
        type: Object,
        default: () => {}
      },
      readOnly: {
        type: Boolean,
        default: false
      },
    },
    mounted () {
      tinymce.init({})
      let userToken = this.user.userToken
      if (userToken){
        this.headers['Authorization'] = 'Bearer ' + `${userToken}`
      }
      this.accept = this.accept.split(',').map(item => 'video/' + item).join(',')
    },

    data() {
      return {
        rule: {
          'phone': [{ required: true, message: '请输入11位手机号码', trigger: 'blur', pattern: /^1[0-9]{10}$/ }],
        },
        isLook: false,
        preFixPath,
        uploadImageUrl,
        uploadMediaUrl,
        headers: {},
        uploadMax: SYSTEM_CONFIG.uploadMaxSize * 1024,
        accept: SYSTEM_CONFIG.uploadMediaExtension,
        acceptImg: SYSTEM_CONFIG.uploadImageExtension,
        format: SYSTEM_CONFIG.uploadMediaExtensions,
        uploadList: [],
        modalVd: false,
        init: {
          language_url: '//misc.hzzcckj.cn/skin/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '//misc.hzzcckj.cn/skin/tinymce/skins/lightgray',
          height: 300,
          plugins: 'link lists image code table colorpicker textcolor contextmenu ',
          toolbar:
            'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat',
      
          branding: false,
          images_upload_handler: (blobInfo, success, failure) =>{
            this.handleImgUpload(blobInfo, success, failure)
          },
          setup: (ed)=> {
            ed.addButton('vedio', {
              // title: '上传视频',
              // image: '/static/tinymce/vedio.jpg',
              icon: 'media',
              tooltip: '上传视频',
              onclick: ()=> {
                this.uploadList = []
                this.modalVd = true
              }
            })
          }
        
        },
        contractTypeList: [{ value: '0', text: '待生效', disabled: false }, { value: '1', text: '生效', disabled: false }, { value: '2', text: '失效', disabled: false }],
      }
    },
    methods: {
      handleImgUpload(blobInfo, success, failure) {
        var xhr, formData
        xhr = new XMLHttpRequest()
        let bolb = blobInfo.blob()
        let self = this
        if (this.uploadMax > 0 && bolb.size > this.uploadMax * 1024) { //bolb.size的单位B,this.uploadMax的单位是kb
          this.$Notice.warning({
            title: '超出文件大小限制',
            desc: '文件 ' + bolb.name + ' 太大，不能超过 ' + parseInt(this.uploadMax / 1024) + 'M。'
          })
          return
        }
        if (this.acceptImg.indexOf(bolb.type.substring(6, bolb.type.length)) < 0) {
          this.$Notice.warning({
            title: '文件格式不正确',
            desc: '文件 ' + bolb.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
          })
          return
        } 
        xhr.open('post', this.uploadImageUrl)
        xhr.setRequestHeader('Authorization', 'Bearer ' + this.user.userToken)
        xhr.responseType = 'json'
        formData = new FormData()
        formData.append('file', bolb, bolb.name)
        xhr.send(formData)
        xhr.onload = function(e ) {
          let res = xhr.response
          if (typeof res === 'string') {
            res = JSON.parse(res)
          }
          if(res.code === 200){
            success(self.preFixPath + res.data.path)
          } else {
            self.$Notice.error({
              title: '上传失败',
              desc: res.message
            })
          }
        }
      },
      setDisabed() {
        let item = { value: '0', text: '待生效', disabled: true }
        this.$set(this.contractTypeList, 0 , item)
      }
    },
  }
</script>
